<template>
  <div style="background-color: white;">
    <div style="display: flex;">
      <div style="padding-left: 20px;padding-top: 10px;color: #4FC1E9;">
        <tiny-alert description="扫描销售票据快速退包装物" :closable="false" />
      </div>
      <div style="flex: 1;text-align: right;padding-top: 10px;padding-right: 10px;">
        <JButton   @click="addGoods" size="small" type="info">查看快速退货商品</JButton>
<!--        <JButton   @click="search" size="small" type="info">查看</JButton>-->
      </div>
    </div>
    <div>
      <div style="display: flex; margin-top: 10px">
        <div style="height: 280px;background-color: white;padding: 10px;margin-right: 30px;">
          <x-form v-model="model" v-model:api="fApi" :rules="formRules"></x-form>
        </div>
        <div style="margin-left: 10px; flex: 1">
          <j-grid :height="300"
                  ref="obillRef"
                  :grid-height="280"
                  :columns="oldColumns"
                  all-fields
                  :show-page="false"
                  :show-footer="false"
                  bind-data
                  v-model="oldList"
          />
        </div>
      </div>
      <tiny-divider />
      <div style="margin-top: 10px;background-color: white;padding: 10px;">
        <div style="margin-bottom: 10px;">
          <table>
            <tbody>
            <tr>
              <td>退货日期：</td>
              <td> <JPicker v-model="billDate" /></td>
              <td style="padding-left: 10px;">备注：</td>
              <td style="width: 300px;"><JInput size="small" v-model="remark" /></td>
              <td style="padding-left: 20px;">
                <JButton @click="toAccounted" ref="btnRef" type="info"   >保存并审核</JButton>
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        <div class="back-goods"  >
          <JGrid ref="jgridBackRef"
                 :columns="fields" :show-page="false"
                 :offset-bottom="30" @edit-closed="editClosed"
                 v-model="goodsModel"
                 bind-data
                 size="small"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref,onActivated,onDeactivated} from "vue";
import tool from '@/utils/tool'
import bus from '@/store/bus'
import JPicker from "@/lui/JPicker.vue";
import JAuto from "@/lui/JAuto.vue";
import {useRouter} from "vue-router";
import JDeliver from "@/lui/JDeliver.vue";
const router = useRouter()
const fApi = ref({})
const altDate = ref(true)
const isRelate = ref(true)
const oldColumns = ref([
  {  width: 40, type: 'index' },
  { field: 'invName', title: '商品名称', width: 280, align: 'left' },
  { field: 'spec', title: '规格', width: 70, align: 'center' },
  { field: 'unit', title: '单位', width: 70, align: 'center' },
  { field: 'assQty', title: '辅助数量', width: 80, align: 'right' },
  { field: 'price', title: '单价', width: 80, align: 'right',formatter: 'formatMoney', },
  { field: 'deduction', title: '返现', width: 80, align: 'right',formatter: 'formatMoney', },
  { field: 'amount', title: '金额', width: 80, align: 'right',formatter: 'formatMoney',  }
])
const fields = ref([
  { type: 'index', width: 50 },
  { field: 'locationName', title: '仓库', width: 80, align: 'left' },
  { field: 'invName', title: '商品名称', width: 205, align: 'left' },
  { field: 'spec', title: '规格', width: 70, align: 'center' },
  { field: 'locationName', title: '仓库', width: 70, align: 'center' },
  { field: 'unit', title: '单位', width: 70, align: 'center' },
  {
    field: 'qty',
    title: '退货数量',
    width: 80,
    align: 'right',
    sum: true,
    editor: { component: 'input', autoselect: true }
  },
  {
    field: 'price',
    title: '退货单价',
    width: 80,
    align: 'right',
    editor: { component: 'input', autoselect: true }
  },
  { field: 'amount', title: '退货金额', width: 80, align: 'right', formatter: 'formatMoney',sum: true },
  { field: 'remark', title: '备注', width: 150, align: 'center', editor: { component: 'input', autoselect: true } }
])
const oldList = ref([])
const goodsModel = ref([])
const invId = ref('')
const price = ref('')
const invName = ref('')
const amount = ref('')
const model = ref({})
const hasHist = ref(0)
const histList = ref([])
const showHistPop = ref(false)
const billDate = ref('')
const currentMenuId = ref(0)
const remark = ref('')
const obillRef = ref()
const jgridBackRef = ref()
const formRules = ref([
  {field: '',title: '状态', com: 'JLabel'},
  {field: 'billDate',title: '日期', com: 'JPicker', width: 220},
  {
    field: 'billNo',title: '票号', com: 'JLabel',canClick: true,
    events: {
      click: () => {
        routeTo(model.value.billNo)
      }
    }
  },
  {field: 'arrears',title: '欠款', com: 'JLabel',price: true},
  {field: 'buName',title: '客户', com: 'JLabel' },
  {field: 'salesName',idField:'salesId',title: '业务员', com: 'JAuto', cat: 'adminList'},
  {field: 'deliverNames',idField: 'deliverIds',title: '送货员', com: 'JDeliver',cat:"deliverList"},
  {field: 'remark',title: '备注', com: 'JInput'},
])
onActivated(() => {
  bus.$on('scan-ret', scanRet)
})
onDeactivated(() => {
  bus.$off('scan-ret', scanRet)
})
const search = () => {
  scanRet({code: '150601-971151'})
}
const  scanRet = ({ code }) => {
  let arr = code.split('-')
  if ([150601, 150602, 150603].indexOf(tool.xe.toNumber(arr[0])) === -1) {
    return tool.err('不是销售单')
  }
  scanRets(code)
}
const scanRets = (code) => {
  tool.post('scan/toBack', { code: code }, true).then((ret) => {
    if (ret.stat) {
      let goods = ret.data.goods
      if (goods.length === 0) {
        return tool.err('还没有快速退货商品')
      }
      let data = ret.data
      // hasHist.value = data.hasHist
      oldList.value = data.oldList
      model.value = data
      //
      if (data.billState === 'draft') {
        billDate.value = tool.getDay().substring(0, 10)
      } else {
        billDate.value = data.billDate
      }
      goodsModel.value = data.goods
    }
  })
}
const routeTo = (billNo) => {
  if(billNo) {
    tool.data.set('query', { billNo })
    if(billNo.indexOf('XS') === 0) {
      router.push({name: 's-in'})
    }
    if(billNo.indexOf('XH') === 0) {
      router.push({name: 's-t'})
    }
    if(billNo.indexOf('XT') === 0) {
      router.push({name: 's-out'})
    }
  }
}
const editClosed = ( cell ) => {
  let field = cell.column.property
  let row = cell.row
  if (field === 'qty') {
    row.qty = tool.xe.toNumber(row.qty)
    row.amount = tool.xe.multiply(row.qty, row.price)
    amount.value = tool.xe.toFixed(tool.xe.sum(model.value.goods, 'amount'), 2)
  }
  if (field === 'price') {
    row.price = tool.xe.toNumber(row.price)
    row.amount = tool.xe.multiply(row.price, row.qty)
    amount.value = tool.xe.toFixed(tool.xe.sum(model.value.goods, 'amount'), 2)
  }
}
// 显示历史关联票据
const showHist = () => {
  if (!model.value.id) return tool.err('没有原始票据')
  tool.post('scan/getHistBackById', { billId: model.value.id }).then((ret) => {
    histList.value = []
    if (ret.data.length > 0) {
      histList.value = ret.data
    }
    if (histList.value.length > 0) {
      showHistPop.value = true
    } else {
      tool.err('没有关联票据')
    }
  })
}
const toAccounted = () => {
  if (!model.value.id) {
    return tool.err('请扫描单据')
  }
  let goods = goodsModel.value
  if (!goods) return
  if (goods.length === 0) return
  let g = goods.filter((row) => {
    return tool.xe.toNumber(row.qty) > 0
  })
  if (g.length === 0) {
    return tool.err('至少输入一行数量')
  }
  model.value.menuId = currentMenuId.value
  model.value.infos = g
  model.value.altDate = altDate.value
  model.value.tuiBillDate = billDate.value
  model.value.tuiRemark = remark.value

  tool.post('bill/saveSaleBack', { isRelate: isRelate.value, data: model.value }).then((ret) => {
    if (ret.stat) {
      model.value = {}
      billDate.value = ''
      oldList.value = []
      remark.value = ''
      amount.value = ''
      hasHist.value = 0
      oldList.value = []
      goodsModel.value = []
    }
  })
}

// 弹出 新增 商品
const editorApi = ref()
const addGoods = () => {
  let options = {
    title: '快速退货商品',
    width: 800,
    height: 600,
    mounted: (api) => {
      editorApi.value = api
      options.getList(api)
    },
    rules: [
      {field: 'des', title: '说明',com: 'JLabel',defaultValue: '列表中的商品可以通过扫描销售单自动填充。'},
      {field: 'invName',idField: 'invId', title: '商品',com: 'JAuto' ,cat: 'goods',required: true},
      {field: 'price', title: '退货单价',com: 'JInput',width: 260,required: true},
      {
        field: '', title: ' ',com: 'JButton',width: 260,text: '新增',
        events: {
          click: () => {
            if(editorApi.value.valid()) {
              options.save()
            }
          }
        }
      },
      {
        field: 'backGrid', title: ' ',com: 'JGrid',height: 400, width: 750,
        columns: [
          {field: '', title: '', width: 40,type: 'index'},
          {field: 'invName', title: '商品名称', width: 300, align: 'left'},
          {field: 'spec', title: '规格', width: 80, align: 'center'},
          {field: 'unit1', title: '单位', width: 80, align: 'center'},
          {field: 'price', title: '退货单价', width: 120, align: 'right', formatter: 'formatMoney'},
          {
            title: '操作', width: 70, slots: { default: 'op' },align: 'center',
            btns: [{label: '删除', click: (row) => {
                options.removeRowEvent(row)
              }}]
          }
        ]
      },
    ],
    getList: (api) => {
      tool.post('bill/getBackGoods', {invId: invId.value, price: price.value},true).then(ret => {
        if (ret.stat) {
          api.exec('backGrid', 'setData', ret.data)
        }
      })
    },
    removeRowEvent: (row) => {
      tool.post('bill/delBackGoods', {id: row.id}).then(ret => {
        if (ret.stat) {
          editorApi.value.exec('backGrid', 'setData', ret.data)
        }
      })
    },
    save: () => {
      let formData = editorApi.value.getFormData()
      let invId = formData.invId
      let price = formData.price
      if (!invId) return tool.err('请选择商品')
      if (!price) return tool.err('请输入退货单价')
      tool.post('bill/saveBackGoods', {invId: invId, price: price}, true).then(ret => {
        if (ret.stat) {
          editorApi.value.setValue('invName', '')
          editorApi.value.setValue('invId', '')
          editorApi.value.setValue('price', '')
          options.getList(editorApi.value)
        }
      })
    }
  }
  tool.editor(options)
}






</script>

<style scoped lang="scss">
.info {
  .label {
    display: inline-block;
    width: 60px;
    font-size: 13px;
    color: #808695;
  }
  .value {
    display: inline-block;
    font-size: 13px;
    height: 31px;
  }
}
td {
  color: #515a6e;
}
.back-goods {
  overflow: auto;
  th {
    font-size: 14px;
  }
  td {
    font-size: 14px;
    background-color: white;
  }
  th,
  td {
    border: 1px solid #e8eaec;
    height: 35px;
    padding: 0 2px;
  }
  .text-center {
    text-align: center;
  }
  .text-right {
    text-align: right;
  }
}
.hist-list {
  margin-top: 10px;
  display: inline-block;
  height: 500px;
  overflow: auto;
  fieldset {
    border: 1px solid #c5c8ce;
    padding: 5px;
  }
}
.bill-draft {
  color: yellowgreen;
}
.bill-accounted {
  color: #f56c6c;
}
</style>